/*
 * SetStore.h
 *
 *  Created on: Apr 19, 2011
 *      Author: burek
 */

#ifndef SETSTORE_H_
#define SETSTORE_H_

#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cstdio>

class KeyValuePair
{
public:
	char * key;
	char * value;

	KeyValuePair(const char * k, const char * v)
	{
		if(k == NULL || v == NULL)
		{
			key = value = NULL;
			return;
		}

		int l1 = strlen(k);
		int l2 = strlen(v);

		key = (char*)malloc(l1 + 1);
		value = (char*)malloc(l2 + 1);

		strcpy(key, k);
		strcpy(value, v);
	}

	~KeyValuePair()
	{
		if(key) free(key);
		if(value) free(value);
	}

	void setKey(const char * k)
	{
		if(k == NULL) return;

		unsigned int nl = strlen(k);
		if(key == NULL)
		{
			key = (char*)malloc(nl + 1);
		}
		else if(strlen(key) < nl)
		{
			char *old_key = key;
			key = (char*)realloc(key, nl + 1);
			if(key == NULL)
			{
				key = old_key;
				return;
			}
		}
		strcpy(key, k);
	}

	void setValue(const char * k)
	{
		if(k == NULL) return;

		unsigned int nl = strlen(k);
		if(value == NULL)
		{
			value = (char*)malloc(nl + 1);
		}
		else if(strlen(value) < nl)
		{
			char *old_value = value;
			value = (char*)realloc(value, nl + 1);
			if(value == NULL)
			{
				value = old_value;
				return;
			}
		}
		strcpy(value, k);
	}

	void setValInt(int x)
	{
		char buffer[32];
		sprintf(buffer, "%d", x);
		setValue(buffer);
	}

	void setValFloat(float x)
	{
		char buffer[32];
		sprintf(buffer, "%f", x);
		setValue(buffer);
	}

	int getValInt(int def)
	{
		if(value == NULL) return def;
		int n = def;
		sscanf(value, "%d", &n);
		return n;
	}

	int getValUXInt(unsigned int def)
	{
		if(value == NULL) return def;
		unsigned int n = def;
		sscanf(value, "%x", &n);
		return n;
	}

	float getValFloat(float def)
	{
		if(value == NULL) return def;
		float n = def;
		sscanf(value, "%f", &n);
		return n;
	}

	void parseLine(char * buffer)
	{
		char * l = strchr(buffer, '=');
		if(l == NULL) return;

		char Key[256];
		memcpy(Key, buffer, l - buffer);
		Key[l - buffer] = '\0';

		int len = strlen(buffer);
		for(int i = 0; i < len; ++i)
		{
			if(buffer[i] == '\n') buffer[i] = '\0';
			if(buffer[i] == '\r') buffer[i] = '\0';
		}

		setKey(Key);
		setValue(l + 1);
	}

	KeyValuePair(char * line)
	{
		parseLine(line);
	}
};

#endif /* SETSTORE_H_ */
